package com.iframework.anson;

import java.util.List;

import com.google.gson.Gson;
import com.iframework.model.json.Chapter.Chapter_List;
import com.iframework.model.json.Chapter.Mix.Chapter_MixToc;
import com.iframework.tools.ApiUtil;
import com.iframework.tools.BaseTools;
import com.iframework.tools.DBHelp_JDBC_MySQL;
import com.iframework.tools.JSONUtil;

public class ChapterManager {
	private static int _type;

	/**
	 * @return type
	 */
	public static int getType() {
		return _type == 0 ? 1 : _type;
	}

	/**
	 * @param type
	 *            要设置的 type
	 */
	public static void setType(int type) {
		_type = type;
	}

	/**
	 * 章节来源
	 * 
	 * @param bookId
	 *            本地Id
	 * @param _bookId
	 *            远程Id
	 * @author Anson
	 */
	public static void getChapter(String bookId, String _bookId,String bookName) {
		Gson gson = new Gson();
		String chaptersJSON = toc(_bookId);
		if (chaptersJSON.equals("") || JSONUtil.checkJson(chaptersJSON, Chapter_List.class) == false) {
			chaptersJSON = mix(_bookId);
		}
		if (!chaptersJSON.equals("")) {
			if (getType() == 4) {
				Chapter_MixToc chapters_Mix = gson.fromJson(chaptersJSON, Chapter_MixToc.class);
				saveChapter(bookId, chapters_Mix, _type,bookName);
			} else {
				Chapter_List chapters = gson.fromJson(chaptersJSON, Chapter_List.class);
				saveChapter(bookId, chapters, _type,bookName);
			}

		}
	}

	/**
	 * 保存章节信息至数据库
	 * 
	 * @param bookId
	 *            书籍本地Id
	 * @param object
	 *            Gson对象
	 * @param type
	 *            章节获取类型：1:atoc；2:btoc；3:ctoc；4:mix
	 * @author Anson
	 */
	private static void saveChapter(String bookId, Object object, int type,String bookName) {
		// 表名
		String tabName = "tbl_chapters";
		// 表字段
		String[] tab_fields = { "type", "title", "link", "currency", "unreadble", "isVip", "bookID", "updated" };
		String[] u_fields = { "title", "link", "type", "currency", "unreadble", "isVip", "updated" };
		String[] q_fields = { "title", "link", "type" };// 章节来源与书籍不同，查询字段也不一样
		String[] r_fields =new String[] { "id", "link" };
		String strNowTime = BaseTools.getNow();
		if (type == 4) {
			Chapter_MixToc chapters_mix = (Chapter_MixToc) object;
			// 更新书籍信息
			// DBHelp_JDBC_MySQL.update("tbl_book", new String[] {"updated"},
			// new String[] {strNowTime}, new String[] {"_id"}, new String[]
			// {chapters_mix.getMixToc().getBook()});

			if (chapters_mix.getOk()) {
				List<com.iframework.model.json.Chapter.Mix.Chapters> chapters = chapters_mix.getMixToc().getChapters();
				while (chapters.iterator().hasNext()) {
					com.iframework.model.json.Chapter.Mix.Chapters chapter = chapters.get(0);
					String[] q_data = { chapter.getTitle(), chapter.getLink(), String.valueOf(type) };// 本地Id
					String[] q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data,
							r_fields);
					if (q_result == null) {
						chapters.remove(chapter);
						continue;
					}
					if (q_result.length > 0 && q_result[0] == null) {
						String[] data = { String.valueOf(type), chapter.getTitle(), chapter.getLink(),
								String.valueOf(0.0f), String.valueOf(chapter.getUnreadble()), String.valueOf(false),
								bookId, strNowTime };
						DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,bookName+" - "+chapter.getTitle());
					} else {
						//对比是否需要更新章节地址,不更新就插入新地址
						if (!chapter.getLink().equals(q_result[1])) {
							String[] u_data = { chapter.getTitle(), chapter.getLink(), String.valueOf(type),
									String.valueOf(0.0f), String.valueOf(chapter.getUnreadble()), String.valueOf(false),
									bookId, strNowTime };
							DBHelp_JDBC_MySQL.update(tabName, u_fields, u_data, q_fields, q_data, bookName+" - "+chapter.getTitle());
						}else{
							String[] data = { String.valueOf(type), chapter.getTitle(), chapter.getLink(),
									String.valueOf(0.0f), String.valueOf(chapter.getUnreadble()), String.valueOf(false),
									bookId, strNowTime };
							DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,bookName+" - "+chapter.getTitle());
						}
					}
					chapters.remove(chapter);
				}
			// BaseTools.log(chapters.getMixToc().getChapters().get(0).getTitle());
		} else {
			Chapter_List chapters_List = (Chapter_List) object;
			DBHelp_JDBC_MySQL.update("tbl_booksource", new String[] { "updated" }, new String[] { strNowTime },
					new String[] { "_id" }, new String[] { chapters_List.get_id() },bookName);

			List<com.iframework.model.json.Chapter.Chapters> chapters = chapters_List.getChapters();
			while (chapters.iterator().hasNext()) {
				com.iframework.model.json.Chapter.Chapters chapter = chapters.get(0);
				String[] q_data = { chapter.getTitle(), chapter.getLink() };// 本地Id
				String[] q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data, r_fields);
				if (q_result == null) {
					chapters.remove(chapter);
					continue;
				}
				if (q_result.length > 0 && q_result[0] == null) {
					String[] data = { String.valueOf(type), chapter.getTitle(), chapter.getLink(),
							String.valueOf(chapter.getCurrency()), String.valueOf(chapter.getUnreadble()),
							String.valueOf(chapter.getIsVip()), bookId, strNowTime };
					DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,bookName+" - "+chapter.getTitle());
				} else {
					//对比是否需要更新章节地址,不更新就插入新地址
					if (!chapter.getLink().equals(q_result[1])) {
						String[] u_data = { chapter.getTitle(), chapter.getLink(), String.valueOf(type),
								String.valueOf(chapter.getCurrency()), String.valueOf(chapter.getUnreadble()),
								String.valueOf(chapter.getIsVip()), bookId, strNowTime };
						DBHelp_JDBC_MySQL.update(tabName, u_fields, u_data, q_fields, q_data,bookName+" - "+chapter.getTitle());
					}else{
						String[] data = { String.valueOf(type), chapter.getTitle(), chapter.getLink(),
								String.valueOf(chapter.getCurrency()), String.valueOf(chapter.getUnreadble()),
								String.valueOf(chapter.getIsVip()), bookId, strNowTime };
						DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,bookName+" - "+chapter.getTitle());
					}
				}
				chapters.remove(chapter);
			}
			// BaseTools.log(chapters.getChapters().get(0).getTitle());
			}
		}
	}

	private static String toc(String _bookId) {
		String strJSON = "";
		for (int i = 1; i < 4; i++) {
			setType(i);
			try {
				strJSON = JSONUtil.toc(_bookId, i, "http://api.zhuishushenqi.com/%s/%s?view=chapters");
				if (strJSON.equals("")) {
					continue;
				} else if (!JSONUtil.checkJson(strJSON, Chapter_List.class))
					break;
				else {
					break;
				}
			} catch (Exception e) {
				return "";
			}
		}
		return strJSON;
	}

	private static String mix(String _bookId) {
		setType(4);
		String url = String.format("http://api.zhuishushenqi.com/mix-toc/%s", _bookId);
		String strJSON = "";
		try {
			strJSON = ApiUtil.send(url);
		} catch (Exception e) {
			return "";
		}
		return strJSON;
	}

}
